package com.example.juc.threadPool.futureTask;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

public class TestFutureTask {

    public static void main(String[] args) throws ExecutionException, InterruptedException {


        ExecutorService executorService = Executors.newFixedThreadPool(3);
//        FutureTask<String> futureTask = new FutureTask<>(new MyTask());
//        Thread t1 = new Thread(futureTask,"t1");
//        t1.start();
//
//        System.out.println(futureTask.get());
//        int i = 10;
//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() ->{
//            System.out.println("进入第一个方法");
//            return Test111.method1(i);
//        },executorService).thenApply((w) ->{
//            System.out.println("进入第二个方法,输入参数="+w);
//            return Test111.method2(w);
//        }).thenApplyAsync(w -> {
//            System.out.println("进入第三个方法,输入参数="+w);
//            return Test111.method3(w);
//        }).whenComplete((w,e) ->{
//            System.out.println("计算完成，结果="+w);
//        }).exceptionally(e ->{
//            System.out.println("计算失败，错误信息=" + e.getMessage());
//            return 0;
//        });
//
//        System.out.println("主线程在做自己的事");

        long start = System.currentTimeMillis();

        List<Integer> parames = Arrays.asList(1, 2, 3, 4, 5, 6);

        List<Integer> result = new ArrayList<>();

        List<CompletableFuture<Integer>> completableFutures = new ArrayList<>();



        parames.forEach(item -> {
            completableFutures.add(CompletableFuture.supplyAsync(() -> Test111.method1(item), executorService));
        });
        for(int k = 0; k < completableFutures.size();k++){
            result.add(completableFutures.get(k).get());
//            completableFutures.get(k).whenComplete((v,e) ->{
//                sss(v);
////                result.add(v);
//            }).exceptionally(e ->{
//                System.out.println("计算失败");
//                return null;
//            });
//            if(k == completableFutures.size() - 1){
//                long costTime = (System.currentTimeMillis() - start) / 1000;
//                System.out.println("计算结果，result=" + result + "耗时" + costTime);
//            }
        }
        long costTime = (System.currentTimeMillis() - start) / 1000;
                System.out.println("计算结果，result=" + result + "耗时" + costTime);
        executorService.shutdown();
    }

    public static void sss(Integer i ){
        System.out.println("处理"+i);
    }
}

    class MyTask implements Callable<String> {

        @Override
        public String call() throws Exception {
            System.out.println("进入call方法");
            return "hello future";
        }
    }


